<template>
  <div class="venue-container">
	<el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	        <el-col :span="24" class="text-center">
	            <div class="title-wrapper">
	            <i class="el-icon-search el-icon--large"></i>
	            <h1 class="main-title">场馆预约管理系统</h1>
	            <p class="sub-title">每一条场馆预约信息，都承载着活动的期待；每一次精准管理，都是对资源高效利用的守护，让场地服务更贴心</p>
	            </div>
	        </el-col>
	    </el-row>
    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="场馆详情"
      width="70%"
      destroy-on-close
      :before-close="handleDialogClose"
    >
      <el-descriptions title="场馆信息" direction="vertical" :column="2" border class="detail-descriptions">
        <el-descriptions-item label="场馆ID">{{ detailData.venueId }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ detailData.status }}</el-descriptions-item>
        <el-descriptions-item label="场馆名称">{{ detailData.venueName }}</el-descriptions-item>
        <el-descriptions-item label="场馆类型">{{ detailData.venueType }}</el-descriptions-item>
        <el-descriptions-item label="分馆名称">{{ detailData.branchName || '无' }}</el-descriptions-item>
        <el-descriptions-item label="开放时间">{{ detailData.openingTime }}</el-descriptions-item>
        <el-descriptions-item label="关闭时间">{{ detailData.closingTime }}</el-descriptions-item>
        <el-descriptions-item label="地址" :span="2">{{ detailData.address || '无' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editVisible"
      title="编辑场馆信息"
      width="50%"
      destroy-on-close
      :before-close="handleDialogClose"
    >
      <el-form 
        :model="editForm" 
        ref="editFormRef" 
        label-width="120px"
        class="form-container"
      >
        <el-form-item label="场馆ID" prop="venueId">
          <el-input v-model="editForm.venueId" disabled></el-input>
        </el-form-item>
        <el-form-item label="场馆名称" prop="venueName" required>
          <el-input v-model="editForm.venueName"></el-input>
        </el-form-item>
        <el-form-item label="分馆名称" prop="branchName">
          <el-input v-model="editForm.branchName"></el-input>
        </el-form-item>
        <el-form-item label="场馆类型" prop="venueType" required>
          <el-input v-model="editForm.venueType"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status" required>
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="operating" value="operating"></el-option>
            <el-option label="closed" value="closed"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开放时间" prop="openingTime" required>
          <el-time-picker
            v-model="editForm.openingTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="选择开放时间"
          ></el-time-picker>
        </el-form-item>
        <el-form-item label="关闭时间" prop="closingTime" required>
          <el-time-picker
            v-model="editForm.closingTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="选择关闭时间"
          ></el-time-picker>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 新增对话框 -->
    <el-dialog
      v-model="addVisible"
      title="新增场馆"
      width="50%"
      destroy-on-close
      :before-close="handleDialogClose"
    >
      <el-form 
        :model="addForm" 
        :rules="rules" 
        ref="addFormRef" 
        label-width="120px"
        class="form-container"
      >
        <el-form-item label="场馆名称" prop="venueName" required>
          <el-input v-model="addForm.venueName"></el-input>
        </el-form-item>
        <el-form-item label="分馆名称" prop="branchName">
          <el-input v-model="addForm.branchName"></el-input>
        </el-form-item>
        <el-form-item label="场馆类型" prop="venueType" required>
          <el-input v-model="addForm.venueType"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status" required>
          <el-select v-model="addForm.status" placeholder="请选择状态">
            <el-option label="operating" value="operating"></el-option>
            <el-option label="closed" value="closed"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开放时间" prop="openingTime" required>
          <el-time-picker
            v-model="addForm.openingTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="选择开放时间"
          ></el-time-picker>
        </el-form-item>
        <el-form-item label="关闭时间" prop="closingTime" required>
          <el-time-picker
            v-model="addForm.closingTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="选择关闭时间"
          ></el-time-picker>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="addForm.address" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAdd">提交</el-button>
      </template>
    </el-dialog>

    <!-- 搜索和操作区 -->
    <div class="search-and-action">
      <!-- 查询区域 -->
      <div class="search-container">
        <el-row :gutter="15" class="search-row">
          <!-- 按名称查询 -->
          <el-col :span="8">
            <el-input 
              placeholder="按名称查询" 
              v-model="searchExactName" 
              @keyup.enter="getVenuesByName"
              class="search-input"
            >
			
              <template #append>
                <el-button @click="getVenuesByName" icon="el-icon-search" size="small"></el-button>
              </template>
            </el-input>
          </el-col>
          
          <!-- 按类型查询 -->
          <el-col :span="8">
            <el-select 
              v-model="searchExactType" 
              placeholder="按类型查询" 
              @change="getVenuesByType"
              class="search-select"
            >
              <el-option label="全部类型" value=""></el-option>
              <el-option label="活动室" value="活动室"></el-option>
              <el-option label="体育馆" value="体育馆"></el-option>
              <el-option label="会议室" value="会议室"></el-option>
              <el-option label="图书馆" value="图书馆"></el-option>
            </el-select>
          </el-col>
          
          <!-- 按状态查询 -->
          <el-col :span="8">
            <el-select 
              v-model="searchExactStatus" 
              placeholder="按状态查询" 
              @change="getVenuesByStatus"
              class="search-select"
            >
              <el-option label="全部状态" value=""></el-option>
              <el-option label="operating" value="operating"></el-option>
              <el-option label="closed" value="closed"></el-option>
            </el-select>
          </el-col>
        </el-row>
      </div>
      
      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button 
          type="primary" 
          icon="el-icon-refresh" 
          @click="getAllVenues"
          class="refresh-btn"
        >
          刷新
        </el-button>
        <el-button 
          type="success" 
          icon="el-icon-plus" 
          @click="openAddDialog"
          class="add-btn"
        >
          新增场馆
        </el-button>
      </div>
    </div>

    <!-- 场馆表格 -->
    <el-table 
      :data="venueData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
      border 
      style="width: 100%;"
      height="450"
      v-loading="loading"
      element-loading-text="加载中..."
      class="venue-table"
    >
      <el-table-column prop="venueId" label="场馆ID" width="100" align="center"></el-table-column>
      <el-table-column prop="venueName" label="场馆名称" width="180" align="center"></el-table-column>
      <el-table-column prop="branchName" label="分馆名称" width="150" align="center"></el-table-column>
      <el-table-column prop="venueType" label="场馆类型" width="120" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag effect="light">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="openingTime" label="开放时间" width="120" align="center"></el-table-column>
      <el-table-column prop="closingTime" label="关闭时间" width="120" align="center"></el-table-column>
      <el-table-column prop="address" label="地址" align="center"></el-table-column>
      <el-table-column label="操作" width="240" fixed="right">
        <template #default="scope">
          <div class="operation-buttons">
            <el-button type="primary" size="mini" icon="el-icon-view" @click="openDetail(scope.row)">查看</el-button>
            <el-button type="warning" size="mini" icon="el-icon-edit" @click="openEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteVenue(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination 
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]" 
        :page-size="pageSize" 
        :total="venueData.length"
        layout="total, sizes, prev, pager, next, jumper"
        class="pagination"
      ></el-pagination>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { post, get } from '../../utils/axios.js'
import { ElMessage, ElMessageBox } from 'element-plus'

// 对话框控制
const detailVisible = ref(false)
const editVisible = ref(false)
const addVisible = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)

// 加载状态
const loading = ref(false)

// 搜索参数
const searchExactName = ref('')
const searchExactType = ref('')
const searchExactStatus = ref('')

// 场馆数据
const venueData = ref([])

// 详情数据
const detailData = reactive({
  venueId: '',
  venueName: '',
  branchName: '',
  venueType: '',
  status: '',
  openingTime: '',
  closingTime: '',
  address: ''
})

// 编辑表单
const editForm = reactive({
  venueId: '',
  venueName: '',
  branchName: '',
  venueType: '',
  status: '',
  openingTime: '',
  closingTime: '',
  address: ''
})

// 新增表单
const addForm = reactive({
  venueName: '',
  branchName: '',
  venueType: '',
  status: '',
  openingTime: '',
  closingTime: '',
  address: ''
})

// 表单验证规则
const rules = reactive({
  venueName: [
    { required: true, message: '场馆名称不能为空', trigger: 'blur' }
  ],
  venueType: [
    { required: true, message: '场馆类型不能为空', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  openingTime: [
    { required: true, message: '请选择开放时间', trigger: 'change' }
  ],
  closingTime: [
    { required: true, message: '请选择关闭时间', trigger: 'change' }
  ]
})

// 处理对话框关闭
const handleDialogClose = (done) => {
  done()
}

// 打开详情对话框
function openDetail(row) {
  Object.assign(detailData, row)
  detailVisible.value = true
}

// 打开编辑对话框
function openEdit(row) {
  Object.assign(editForm, row)
  editVisible.value = true
}

// 打开新增对话框
function openAddDialog() {
  // 重置表单
  Object.keys(addForm).forEach(key => {
    addForm[key] = ''
  })
  addVisible.value = true
}

// 分页大小变化
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}

// 当前页变化
function handleCurrentChange(val) {
  currentPage.value = val
}

// 提交编辑
function submitEdit() {
  loading.value = true;
  post('/api/venues/update', editForm, (res) => {
    loading.value = false;
    if (res && (res.success || res.code === 200 || res.status === 1)) {
		console.log('进入成功分支'); // 确认是否执行
      ElMessage.success('更新成功');
      editVisible.value = false;
      getAllVenues();
    } else {
		console.log('进入失败分支');
      ElMessage.error(res?.message || '更新失败');
    }
  }, (error) => {
    loading.value = false;
    ElMessage.error(`更新失败: ${error.message}`);
  });
}

// 提交新增
function submitAdd() {
  loading.value = true
  post('/api/venues/add', addForm, (res) => {
    loading.value = false
    if (res && (res.success || res.code === 200 || res.status === 1)) {
      ElMessage.success('添加成功')
      addVisible.value = false
      getAllVenues()
    } else {
      ElMessage.error(res.message || '添加失败')
    }
  }, (error) => {
    loading.value = false
    ElMessage.error(`添加失败: ${error.message}`)
  })
}

// 删除场馆
function deleteVenue(row) {
  ElMessageBox.confirm(`确定删除场馆 ${row.venueName} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true;
    // 关键修改：参数名从 venueId 改为 id
    post('/api/venues/deleteById', { id: row.venueId }, (res) => {
      loading.value = false;
      if (res && (res.success || res.code === 200 || res.status === 1)) {
        ElMessage.success('删除成功');
        getAllVenues();
      } else {
        ElMessage.error(res?.message || '删除失败');
      }
    }, (error) => {
      loading.value = false;
      ElMessage.error(`删除失败: ${error.message}`);
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

// 按名称查询
function getVenuesByName() {
  if (!searchExactName.value) {
    getAllVenues()
    return
  }
  
  loading.value = true
  get('/api/venues/getByName', { venueName: searchExactName.value }, (res) => {
    loading.value = false
    handleSearchResult(res)
  }, (error) => {
    loading.value = false
    ElMessage.error(`查询失败: ${error.message}`)
  })
}

// 按类型查询
function getVenuesByType() {
  if (!searchExactType.value) {
    getAllVenues()
    return
  }
  
  loading.value = true
  get('/api/venues/getByType', { venueType: searchExactType.value }, (res) => {
    loading.value = false
    handleSearchResult(res)
  }, (error) => {
    loading.value = false
    ElMessage.error(`查询失败: ${error.message}`)
  })
}

// 按状态查询
function getVenuesByStatus() {
  if (!searchExactStatus.value) {
    getAllVenues()
    return
  }
  
  loading.value = true
  get('/api/venues/getByStatus', { status: searchExactStatus.value }, (res) => {
    loading.value = false
    handleSearchResult(res)
  }, (error) => {
    loading.value = false
    ElMessage.error(`查询失败: ${error.message}`)
  })
}

// 获取所有场馆
function getAllVenues() {
  loading.value = true;
  get('/api/venues/getAll', {}, (res) => {
    loading.value = false;
    handleSearchResult(res)
  }, (error) => {
    loading.value = false;
    ElMessage.error(`请求失败: ${error.message}`);
  });
}

// 处理搜索结果
function handleSearchResult(res) {
  if (res.success && Array.isArray(res.data)) {
    venueData.value = res.data
  } else if (Array.isArray(res)) {
    venueData.value = res
  } else if (res.data && Array.isArray(res.data)) {
    venueData.value = res.data
  } else {
    venueData.value = []
  }
  
  if (venueData.value.length > 0) {
    ElMessage.success(`找到 ${venueData.value.length} 条记录`)
  } else {
    ElMessage.warning('未找到匹配记录')
  }
}

// 页面加载时获取所有场馆
onMounted(() => {
  getAllVenues()
})
</script>

<style scoped>
.venue-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

/* 搜索和操作区样式 */
.search-and-action {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.search-container {
  margin-bottom: 15px;
}

.search-row {
  width: 100%;
}

.search-input, .search-select {
  width: 100%;
  transition: all 0.3s ease;
}

.search-input:focus-within, .search-select:focus-within {
  box-shadow: 0 0 0 2px rgba(144, 147, 153, 0.2);
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.refresh-btn, .add-btn {
  transition: all 0.2s ease;
}

.refresh-btn:hover, .add-btn:hover {
  transform: translateY(-2px);
}

/* 表格样式 */
.venue-table {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.venue-table th {
  background-color: #f7f8fa;
  font-weight: 500;
}

.venue-table tr:hover {
  background-color: #fafafa;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  gap: 6px;
  justify-content: center;
}

.operation-buttons .el-button {
  transition: all 0.2s ease;
}

.operation-buttons .el-button:hover {
  transform: scale(1.05);
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.pagination {
  user-select: none;
}

/* 表单样式 */
.form-container {
  padding: 10px 0;
}

.el-form-item {
  margin-bottom: 18px;
}

/* 详情对话框样式 */
.detail-descriptions {
  margin-top: 10px;
}

.detail-descriptions .el-descriptions__cell {
  padding: 12px 15px;
}
:deep(.el-message--success) {
  background-color: #f0f9eb !important;
  border-color: #e1f3d8 !important;
  color: #67c23a !important;
}

:deep(.el-message--success .el-message__icon) {
  color: #67c23a !important;
}
.detail-descriptions .el-descriptions__label {
  background-color: #f7f8fa;
  font-weight: 500;
}

/* 动画效果 */
.el-button, .el-input, .el-select, .el-table {
  transition: all 0.2s ease;
}

.el-dialog {
  animation: dialogFadeIn 0.3s ease;
}

@keyframes dialogFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
